package com.higold.cloud.ui.fragment

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v7.widget.LinearLayoutManager
import com.higold.cloud.R
import com.higold.cloud.base.BaseFragment
import kotlinx.android.synthetic.main.fragment_develop.*
import com.gyf.immersionbar.ktx.immersionBar
import com.higold.cloud.mvp.contract.DevelopListContract
import com.higold.cloud.mvp.model.bean.UploadPic
import com.higold.cloud.mvp.model.bean.developList.DevelopList
import com.higold.cloud.mvp.presenter.DevelopListPresenter
import com.higold.cloud.net.exception.ErrorStatus
import com.higold.cloud.showToast
import com.higold.cloud.ui.adapter.DevelopAdapter
import com.higold.cloud.utils.AppUtils
import com.higold.cloud.utils.StatusBarUtil
import com.higold.cloud.view.DevelopFullScreenPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.SimpleCallback
import me.zhouzhuo.zzimagebox.ZzImageBox
import java.io.File


/**
 *    author : lxz
 *    date   : 2019/8/13 14:38
 *    desc   :
 */

class DevelopFragment : BaseFragment(), DevelopListContract.View {

    private var isFirst: Boolean = true

    private val mPresenter by lazy { DevelopListPresenter() }

    private var mTitle: String? = null

    private var imageUrl: String = ""

    private lateinit var imageBoxAddMode: ZzImageBox

    private lateinit var mAdapter: DevelopAdapter

    private var popup: DevelopFullScreenPopup? = null

    companion object {

        private const val CAMERA_REQUEST_CODE = 3
        val SAVED_IMAGE_PATH = Environment.getExternalStorageDirectory().absolutePath + "/photo/" + System.currentTimeMillis() + ".jpg"
        private const val IMAGE = 1
        private const val REQUEST_CROP = 4

        fun getInstance(title: String): DevelopFragment {
            val fragment = DevelopFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    init {
        mPresenter.attachView(this)
    }

    override fun setUploadPic(uploadPic: UploadPic) {
        multipleStatusView.showContent()
        imageUrl = if (imageUrl == "") {
            uploadPic.data.image
        } else {
            setImageBuilder(uploadPic.data.image)
        }

        setImageBuilder(uploadPic.data.image)
        imageBoxAddMode.addImageOnlineWithRealPathAndType(uploadPic.data.image, "tag" + imageBoxAddMode.count, imageBoxAddMode.count)

    }

    override fun setDevelopList(developList: DevelopList) {
        multipleStatusView.showContent()

        rv_shop_list.layoutManager = LinearLayoutManager(activity)
        mAdapter = DevelopAdapter(developList.data.bodyList)
        rv_shop_list.adapter = mAdapter
        mAdapter.isFirstOnly(false)//init firstOnly state
    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR) {
            multipleStatusView.showNoNetwork()
        } else {
            multipleStatusView.showError()
        }
    }

    override fun showLoading() {
        multipleStatusView.showLoading()
    }

    override fun dismissLoading() {
    }

    override fun lazyLoad() {
        mPresenter.getDevelopList()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
    }

    private fun setImageBuilder(imageUrl: String): String {
        return this.imageUrl + "," + imageUrl
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (userVisibleHint && isFirst) {
            isFirst = !isFirst
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_develop

    override fun initView() {

        popup = DevelopFullScreenPopup(this.context!!)

        sv_content.isNestedScrollingEnabled = false
        rv_shop_list.setHasFixedSize(true)

        tv_push.setOnClickListener {
            XPopup.Builder(context)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onCreated() {
                            activity?.let { it -> StatusBarUtil.darkMode(it) }
                        }
                    })
                    .moveUpToKeyboard(false)
                    .asCustom(popup)
                    .show()
        }

        popup!!.setOnFullScreenPopupClickListener(object : DevelopFullScreenPopup.FullScreenPopupClickListener {
            override fun OnImageClick(imageBoxAddMode: ZzImageBox) {
                this@DevelopFragment.imageBoxAddMode = imageBoxAddMode
                PhotoChoose()
            }

            override fun okClick(data: java.util.ArrayList<String>?) {
                if (data != null) {
                    if (data.size < 10)
                        showToast("请正确填写数据")
                    else
                        showToast("请正确填写数据")
                }
                setStateBar()
            }

            override fun cancelClick() {
                popup!!.dismiss()
                setStateBar()
            }

        })
    }

    private fun setStateBar() {
        immersionBar {
            statusBarColor(R.color.colorAccent)
            titleBarMarginTop(rv_shop_list)
            statusBarDarkFont(false)
            navigationBarDarkIcon(false)
        }
    }


    private fun PhotoChoose() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, DevelopFragment.IMAGE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        //获取图片路径
        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            val selectedImage = data.data
            mPresenter.getUploadPic(getPath(selectedImage))
        }
        if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_REQUEST_CODE) {
            AppUtils.isExist(SAVED_IMAGE_PATH)
            mPresenter.getUploadPic(SAVED_IMAGE_PATH)
        }
        if (requestCode == REQUEST_CROP && resultCode == Activity.RESULT_OK && data != null) {
            if (data.data != null) {
                val bitmap = AppUtils.decodeUriAsBitmap(activity!!.applicationContext, data.data)
                AppUtils.saveBitmap(bitmap!!, SAVED_IMAGE_PATH)
            }
            mPresenter.getUploadPic(getPath(data.data))
        }
    }

    private fun getPath(uri: Uri?): String {
        val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
        val c = activity!!.applicationContext.contentResolver.query(uri, filePathColumns, null, null, null)
        c.moveToFirst()
        val columnIndex = c.getColumnIndex(filePathColumns[0])
        val imagePath = AppUtils.compressImage(c.getString(columnIndex), SAVED_IMAGE_PATH, 30)
        AppUtils.isExist(imagePath)
        c.close()

        return imagePath
    }

}